<?php

namespace Module\Admin;

use Manager\Post as Manager;
use W3\Html;
use W3\Exception;

!defined('W3_ROOT_DIR') AND exit;

/**
 * 文章编辑组件
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Post extends Manager
{
    /**
     * 初始化
     *
     * @access protected
     * @return void
     */
    protected function init()
    {
        /** 必须为贡献者以上权限 */
        $this->auth->check('contributor');

		# 定义变量默认数据
        $this->parameter([

			# 设置主体
			'main' => 'admin.post',
			
			# 分页大小
		    'pageSize'=>20,
			
			# 操作列表
		    'operate'=> [
			    'selectall'=>[
				    'name'=>__('全选'),
					'data-selectall'
				], 
				'delete'=>[
				    'name'=>__('删除'),
					'data-confirm'=>__('删除不可恢复，确定删除？'),
					'href'=>$this->adminUrl('post/delete', false)
				]
			],
			
			# 操作列表
		    'tabs'=> [
			
			    'publish' => [
				    'name' => __('公开'),
				    'href' => $this->request->makeUrl('status=publish&page=1'),
				    'current'=> function($widget){
					    return !$widget->request->status || 'publish' == $widget->request->status;
				    }
			    ],
			
			    'draft' => [
				    'name' => __('草稿'),
				    'href' => $this->request->makeUrl('status=draft&page=1'),
				    'current'=> function($widget){
					    return 'draft' == $widget->request->status;
				    },
					'balloon'=> function($widget){

		                $stat = $this->widget('W3\Stat');
		
		                # 具有编辑以上权限,可以查看所有文章,反之只能查看自己的文章
		                $isAll = $this->auth->check('editor', true) && 'off' != $this->request->all;
						
						return $isAll ? (!isset($this->request->uid) ? $stat->draftPostNum : $stat->currentDraftPostNum) : $stat->myDraftPostNum;
					}
			    ],

			    'waiting' => [
				    'name' => __('待审核'),
				    'href' => $this->request->makeUrl('status=waiting&page=1'),
				    'current'=> function($widget){
					    return 'waiting' == $widget->request->status;
				    },
					'balloon'=> function($widget){

		                $stat = $this->widget('W3\Stat');
		
		                # 具有编辑以上权限,可以查看所有文章,反之只能查看自己的文章
		                $isAll = $this->auth->check('editor', true) && 'off' != $this->request->all;
						
						return $isAll ? (!isset($this->request->uid) ? $stat->waitingPostNum : $stat->currentWaitingPostNum) : $stat->myWaitingPostNum;
					}
			    ],
			
			    'hidden' => [
				    'name' => __('隐藏'),
				    'href' => $this->request->makeUrl('status=hidden&page=1'),
				    'current'=> function($widget){
					    return 'hidden' == $widget->request->status;
				    },
					'balloon'=> function($widget){

		                $stat = $this->widget('W3\Stat');
		
		                # 具有编辑以上权限,可以查看所有文章,反之只能查看自己的文章
		                $isAll = $this->auth->check('editor', true) && 'off' != $this->request->all;
						
						return $isAll ? (!isset($this->request->uid) ? $stat->hiddenPostNum : $stat->currentHiddenPostNum) : $stat->myHiddenPostNum;
					}
			    ],			

		        'all' => [
				    'name' => __('所有'),
					'href' => $this->request->makeUrl('all=on&page=1'),
					'current'=> function($widget){
						return !isset($widget->request->all) || 'on' == $widget->request->get('all');
					},
					'hide' => isset($this->request->uid)
				],
				
			    'me' => [
				    'name' => __('我的'),
				    'href' => $this->request->makeUrl('all=off&page=1'),
				    'current'=> function($widget){
					    return 'off' == $widget->request->get('all');
				    },
					'hide' => isset($this->request->uid)
			    ]
			],
			
			# 状态列表
		    'status'=> [
			    'publish'=>__('公开'),
				'draft'=>__('草稿'),
				'waiting'=>__('待审核'),
				'hidden'=>__('隐藏')
			],
			
		], true);
		
	}
	
    /**
     * 绑定动作
     *
     * @access public
     * @return void
     */
    public function action()
    {
		$this->on(!$this->request->action || $this->request->is('action=index'))->index();
		$this->on($this->request->is('action=edit'))->edit();
		$this->on($this->request->isPost() && $this->request->is('action=edit'))->update();
		$this->on($this->request->is('action=add'))->edit();
		$this->on($this->request->isPost() && $this->request->is('action=add'))->add();
		$this->on($this->request->isPost() && $this->request->is('action=delete'))->delete();
    }

    public function edit()
    {
        if ($this->request->cid) {

            /** 按tag查询 */
            $this->db
				->select()
		        ->from('table.contents')
			    ->where('table.contents.type = ? and table.contents.cid = ?', 'post', $this->request->filter('int')->cid)
			    ->limit(1)
			    ->fetch([$this, 'push']);

            if (!$this->have()) {
				throw new Exception(__('文章不存在'), 404);
            } elseif (!$this->allow('edit')) {
                throw new Exception(__('没有编辑权限'), 403);
            }
        }
		
        /** 更新模式 */
        if ($this->cid) {
			$this->parameter->title = __('编辑文章 %s', [$this->title]);
        } else {
			$this->parameter->title = __('增加文章');
		}
		
		/** 输出内容 */
		$this->layout->set($this->form(), 'body');

		$this->view();
    }
	
    public function index()
    {
		/** 按post查询 */
        $select = $this->db
			->select()
		    ->from('table.contents')
			->where('table.contents.type = ?', 'post');

        /** 按状态查询 */
		$status = isset($this->parameter->status[$this->request->status]) ? $this->request->status : 'publish';
        $select->where('table.contents.status = ?', $status);	
		
        /** 如果具有编辑以上权限,可以查看所有文章,反之只能查看自己的文章 */
        if (!$this->auth->check('editor', true)) {
            $select->where('table.contents.uid = ?', $this->auth->uid);
        } else {
			
			if (isset($this->request->uid)) {
                $select->where('table.contents.uid = ?', $this->request->filter('int')->uid);
			} else if('off' == $this->request->all){
                $select->where('table.contents.uid = ?', $this->auth->uid);
			}
		}	

        /** 过滤分类 */
        if (NULL != ($category = $this->request->category)) {
			$select->join('table.relate', 'table.contents.cid = table.relate.cid')
            ->where('table.relate.mid = ?', $category);
        }

        /** 过滤分类 */
        if (NULL != ($tag = $this->request->tag)) {
			$select->join('table.relate', 'table.contents.cid = table.relate.cid')
            ->where('table.relate.mid = ?', $tag);
        }

        /** 过滤标题 */
        if (NULL != ($keywords = $this->request->filter('search')->keywords)) {
            $select->where('table.contents.title LIKE ?', '%' . $keywords . '%');
        }

		/** 计算数目 */
		$total = $select->count();
		$page = $this->request->get('page', 1);
		$pageUrl = $this->request->makeUrl('page=%page%');

        /** 提交查询 */
        $select
		    ->order('table.contents.cid', 'DESC')
            ->page($page, $this->parameter->pageSize)
			->get([$this, 'push']);
		
		$this->parameter([
			
			# 当前页数
			'page'         => $page,
			
			# 内容总数 
			'total'        => $total, 
			
			# 页面Url
			'pageUrl'      => $pageUrl
			
		]);

		# 版面布局
		$this->layout->set($this->tabs(false), 'top');
		$this->layout->set($this->postList(), 'body');
		$this->layout->set($this->pagination(false), 'bottom');

		$this->view();
    }
	
    public function postList()
    {
		$categories = $this->widget('Category\Rows');

		$form = Html::form()
		    ->method('get')
			->addClass('mb-3');
			
		if (!isset($this->request->tag)) {

            /** 分类 */
            $options = [''=>__('分类')];
            while ($categories->next()) {
                $options[$categories->mid] = str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $categories->level) . $categories->name;
            }
            $category = Html::select('category', $options, $this->request->filter('int')->category)->addClass('mb-2');
		    $form->set($category);
		}
		
		if(isset($this->request->all)){
			$form->set(Html::hidden('all', $this->request->filter('strip_tags')->all));
		}
		
		if(isset($this->request->type)){
			$form->set(Html::hidden('type', $this->request->filter('strip_tags')->type));
		}
		
		if(isset($this->request->status)){
			$form->set(Html::hidden('status', $this->request->filter('strip_tags')->status));
		}

		$keywords = Html::search('keywords', htmlspecialchars($this->request->keywords))->placeholder(__('请输入关键字'));
		
        if (!empty($_GET)){
			$keywords
			    ->reset
				->show()
				->title(__('取消筛选'))
				->href($this->adminUrl('post', false));
	    }
		
		$form->set($keywords);

        if(isset($this->request->uid)){
            $uid = Html::hidden('uid', $this->request->filter('int')->uid);
            $form->set($uid);
        }
		
		$html = $form->render();

        if ($this->have()) {
			$table = Html::table();
			$table->thead->preppend($this->operate(false));
			$table->thead->preppend('
                <colgroup>
				    <col width="3%" />
					<col width="3%" />
                    <col width="35%" />
					<col width="20%" />
					<col />
                </colgroup>
			');
			$table->head([
			    '',
				'',
			    __('标题'),
				__('分类'),
				__('作者'),
				__('日期'),
			]);
			while ($this->next()){
				$mids = explode(',', $this->mids);
				$length = count($mids);
				$cat = '';
                foreach ($mids as $mid){
					if($mid){
					    --$length;
					    $category = $categories->get($mid);
                        $category && $cat .= '<a href="'.$this->request->makeUrl('page=1&category=' . $category['mid']) .'">' . $category['name'] . '</a>' . ($length ? ', ' : '');
				    }
                }
				
			    $table->body([
				    Html::checkbox('cid', [$this->cid => '']),
					'<a class="badge badge-md badge-pill badge-primary-soft mr-2" href="'.$this->adminUrl('comment', 'cid=' . $this->cid, false).'">'.$this->commentsNum.'</a>',
				    '<a href="' .$this->adminUrl('post/edit', 'cid=' . $this->cid, false).'">'.$this->title.'</a>&nbsp;&nbsp;<a target="_blank" class="text-muted" href="'.$this->permalink.'"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-link-2"><path d="M15 7h3a5 5 0 0 1 5 5 5 5 0 0 1-5 5h-3m-6 0H6a5 5 0 0 1-5-5 5 5 0 0 1 5-5h3"></path><line x1="8" y1="12" x2="16" y2="12"></line></svg></a>',
					$cat,
					'<a href="'.$this->request->makeUrl('uid=' . $this->uid).'">'.$this->author->name.'</a>',
					'<span class="text-muted text-sm">' . $this->dateWord . '</span>'		
				]);
			}

			$html .= $table->wrap(Html::form()->removeClass('w3-form'))->render();
		}

		return $html;
	}

	
    /**
     * 发布文章
     *
     * @access public
     * @return void
     */
    public function add()
    {
        $post = [
			'title'         =>  $this->request->get('title', __('未命名文档')),
			'uid'           =>  $this->auth->uid,
			'type'          =>  'post',
			'status'        =>  isset($this->parameter->status[$this->request->status]) ? $this->request->status : 'publish',
            'allowComment'  =>  !empty($this->request->allowComment) ? 1 : 0,
            'intro'         =>  $this->autoIntro($this->request->intro, $this->request->text),
			'mids'          =>  implode(',', $this->request->getArray('mids')),
			'tags'          =>  $this->request->get('tags', ''),
        ];
		
		$form = $this->form();
			
		/** 验证格式 */
        if ($form->validate()) {
            $this->goBack();
        }

		/** 取出数据 */
        $post += $this->request->from(array_keys($form->getInputs()));

		$this->addPost($post);
		
        /** 提示信息 */
        $this->notice(__('文章增加成功'));
		
		$this->redirect($this->adminUrl('post', false));
	}
	 
    public function update()
    {
        $post = [
			'title'         =>  $this->request->get('title', __('未命名文档')),
			'uid'           =>  $this->auth->uid,
			'type'          =>  'post',
			'status'        =>  isset($this->parameter->status[$this->request->status]) ? $this->request->status : 'publish',
            'allowComment'  =>  !empty($this->request->allowComment) ? 1 : 0,
            'intro'         =>  $this->autoIntro($this->request->intro, $this->request->text),
			'mids'          =>  implode(',', $this->request->getArray('mids')),
			'tags'          =>  $this->request->get('tags', ''),
        ];
		
        $post += $this->request->from(array_keys($this->form()->getInputs()));
		$this->updatePost($this->cid, $post);

		// 获取页面偏移的URL Query
        $count = $this->db
		    ->select(1)
		    ->from('table.contents')
			->where('table.contents.cid > ? and table.contents.type = ?', $this->cid, 'post')
			->count() + 1;

        /** 提示信息 */
        $this->notice(__('文章 %s 更新成功', [$this->title]));
		
		$this->redirect($this->adminUrl('post', 'page=' . ceil($count / $this->parameter->pageSize . '&cid=' . $this->theId), false));
    }
    /**
     * 删除文章
     *
     * @access public
     * @return void
     */
    public function delete()
    {
        $cids = $this->request->filter('int')->getArray('cid');
        $deleteCount = 0;
        foreach ($cids as $cid) 
		{
		    if($this->deletePost($cid)){ 
				$deleteCount++;
			}
		}

        /** 设置提示信息 */
        $this->notice(
		    $deleteCount > 0 
			? __('文章已经删除') 
			: __('没有文章被删除'), $deleteCount > 0 ? 'success' : 'notice'
		);
		
		$this->goBack();
    }

}
